package client.view;

import client.DataBuffer;
import client.util.ClientUtil;
import common.model.entity.Request;
import common.model.entity.Response;
import common.model.entity.ResponseStatus;
import common.model.entity.User;

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.List;

/**
 * 登录窗口
 */

public class LoginFrame extends JFrame {
    private static final long serialVersionUID = -3426717670093483287L;
    JTextField idField;
    JPasswordField pwdField;

    public LoginFrame(){
        this.init();
        setVisible(true);
    }

    public void init(){
        setTitle("OO");
        setIconImage(Toolkit.getDefaultToolkit().getImage("images\\logo.png"));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setBounds(550, 300, 441, 336);
        JPanel contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        contentPane.setBackground(Color.WHITE);

        JPanel topPanel = new JPanel();
        topPanel.setBounds(0, 0, 426, 104);
        contentPane.add(topPanel);
        topPanel.setLayout(null);

        JLabel label = new JLabel("");
        label.setIcon(new ImageIcon("images\\logintop.png"));
        label.setBounds(0, 0, 426, 104);
        topPanel.add(label);

        JPanel LoginPanel = new JPanel();
        LoginPanel.setBounds(60, 114, 284, 82);
        contentPane.add(LoginPanel);
        LoginPanel.setLayout(null);
        LoginPanel.setBackground(Color.WHITE);

        JLabel idIcon = new JLabel("");
        idIcon.setIcon(new ImageIcon("images\\account.png"));
        idIcon.setBounds(10, 17, 16, 16);
        LoginPanel.add(idIcon);

        JLabel pwdIcon = new JLabel("");
        pwdIcon.setIcon(new ImageIcon("images\\pwd.png"));
        pwdIcon.setBounds(10, 57, 16, 16);
        LoginPanel.add(pwdIcon);

        idField = new JTextField();
        idField.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        idField.setBounds(43, 10, 231, 28);
        idField.requestFocusInWindow();//用户名获得焦点
        idField.setToolTipText("账号");
        idField.setBorder(new MatteBorder(0, 0, 2, 0, new Color(0, 121, 250, 65)));
        LoginPanel.add(idField);
        idField.setColumns(10);

        pwdField = new JPasswordField();
        pwdField.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        pwdField.setBounds(43, 48, 231, 28);
        idField.setToolTipText("密码");
        pwdField.setBorder(new MatteBorder(0, 0, 2, 0, new Color(0, 121, 250, 35)));
        LoginPanel.add(pwdField);
        pwdField.setColumns(10);

        JLabel registeLabel = new JLabel("注册账号");
        registeLabel.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 12));
        registeLabel.setBounds(10, 267, 53, 22);
        contentPane.add(registeLabel);

        //JLabel loginLable = new ColorfulLabel("1",Color.CYAN);

        JButton loginButton = new JButton("登录");
        loginButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 16));
        loginButton.setBounds(103, 216, 232, 39);
        loginButton.setBackground(Color.LIGHT_GRAY);
        loginButton.setBorderPainted(false);//不绘制边框
        loginButton.setFocusPainted(false);//选中后不绘制边框
        //loginButton.setContentAreaFilled(false);//不绘制按钮区域
        contentPane.add(loginButton);


        setVisible(true);


        //关闭窗口
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                Request req = new Request();
                req.setAction("exit");
                try {
                    ClientUtil.sendTextRequest(req);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }finally{
                    System.exit(0);
                }
            }
        });

        //注册
        registeLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                new RegisterFrame();  //打开注册窗体
            }
        });

        //"登录"
        loginButton.addActionListener(e -> login());


        //文本框下划线
        idField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                idField.setBorder(new MatteBorder(0, 0, 2, 0, new Color(0, 121, 250, 255)));
            }
        });
        idField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                idField.setBorder(new MatteBorder(0, 0, 2, 0, new Color(0, 121, 250, 30)));
            }
        });
        pwdField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                pwdField.setBorder(new MatteBorder(0, 0, 2, 0, new Color(0, 121, 250, 255)));
            }
        });
        pwdField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                pwdField.setBorder(new MatteBorder(0, 0, 2, 0, new Color(0, 121, 250, 27)));
            }
        });
    }


    /** 登录 */
    @SuppressWarnings("unchecked")
    private void login() {
        if ("".equals(idField.getText())
                || "".equals(pwdField.getPassword())) {
            JOptionPane.showMessageDialog(LoginFrame.this,
                    "账号和密码是必填的",
                    "输入有误",JOptionPane.ERROR_MESSAGE);
            idField.requestFocusInWindow();
            return;
        }

        if(!idField.getText().matches("^\\d*$")){
            JOptionPane.showMessageDialog(LoginFrame.this,
                    "账号必须是数字",
                    "输入有误",JOptionPane.ERROR_MESSAGE);
            idField.requestFocusInWindow();
            return;
        }

        Request req = new Request();
        req.setAction("userLogin");
        req.setAttribute("id", idField.getText());
        req.setAttribute("password", new String(pwdField.getPassword()));

        //获取响应
        Response response = null;
        try {
            response = ClientUtil.sendTextRequest(req);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        if(response.getStatus() == ResponseStatus.OK){
            //获取当前用户
            User user2 = (User)response.getData("user");
            if(user2!= null){ //登录成功
                DataBuffer.currentUser = user2;
                //获取当前在线用户列表
                DataBuffer.onlineUsers = (List<User>)response.getData("onlineUsers");

                LoginFrame.this.dispose();
                new MainFrame();  //打开聊天窗体
            }else{ //登录失败
                String str = (String)response.getData("msg");
                JOptionPane.showMessageDialog(LoginFrame.this,
                        str,
                        "登录失败",JOptionPane.ERROR_MESSAGE);
            }
        }else{
            JOptionPane.showMessageDialog(LoginFrame.this,
                    "服务器内部错误，请稍后再试！！！","登录失败",JOptionPane.ERROR_MESSAGE);
        }
    }
}
